package cn.iocoder.yudao.module.biz.service.licence;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.common.util.string.StringUtils;
import cn.iocoder.yudao.module.biz.controller.admin.licence.vo.*;
import cn.iocoder.yudao.module.biz.controller.admin.licenceAnalyzeData.vo.BizLicenceAnalyzeDataExportReqVO;
import cn.iocoder.yudao.module.biz.controller.admin.licenceAudit.vo.BizLicenceAuditExportReqVO;
import cn.iocoder.yudao.module.biz.controller.admin.licenceAudit.vo.BizLicenceAuditRespVO;
import cn.iocoder.yudao.module.biz.controller.admin.licencePerson.vo.BizLicencePersonExportReqVO;
import cn.iocoder.yudao.module.biz.controller.admin.licenceSafeMeasures.vo.BizLicenceSafeMeasuresExportReqVO;
import cn.iocoder.yudao.module.biz.convert.licence.BizLicenceConvert;
import cn.iocoder.yudao.module.biz.convert.licenceAudit.BizLicenceAuditConvert;
import cn.iocoder.yudao.module.biz.dal.dataobject.licence.BizLicenceDO;
import cn.iocoder.yudao.module.biz.dal.dataobject.licenceAnalyzeData.BizLicenceAnalyzeDataDO;
import cn.iocoder.yudao.module.biz.dal.dataobject.licenceAudit.BizLicenceAuditDO;
import cn.iocoder.yudao.module.biz.dal.dataobject.licencePerson.BizLicencePersonDO;
import cn.iocoder.yudao.module.biz.dal.dataobject.licenceSafeMeasures.BizLicenceSafeMeasuresDO;
import cn.iocoder.yudao.module.biz.dal.mysql.licence.BizLicenceMapper;
import cn.iocoder.yudao.module.biz.dal.mysql.licenceAnalyzeData.BizLicenceAnalyzeDataMapper;
import cn.iocoder.yudao.module.biz.dal.mysql.licenceAudit.BizLicenceAuditMapper;
import cn.iocoder.yudao.module.biz.dal.mysql.licencePerson.BizLicencePersonMapper;
import cn.iocoder.yudao.module.biz.dal.mysql.licenceSafeMeasures.BizLicenceSafeMeasuresMapper;
import cn.iocoder.yudao.module.biz.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.infra.service.oss.OssService;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.biz.enums.ErrorCodeConstants.LICENCE_NOT_EXISTS;

/**
 * 危险作业票主 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Lazy(value = false)
public class BizLicenceServiceImpl implements BizLicenceService {


    @Resource
    private BizLicenceMapper licenceMapper;
    @Resource
    private BizLicenceAnalyzeDataMapper licenceAnalyzeDataMapper;
    @Resource
    private BizLicenceSafeMeasuresMapper licenceSafeMeasuresMapper;
    @Resource
    private BizLicencePersonMapper bizLicencePersonMapper;
    @Resource
    BizLicenceAuditMapper licenceAuditMapper;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    private AdminUserMapper userMapper;
    @Resource
    OssService ossService;
    @Resource
    private FileApi fileApi;

    @Value("${pdfFontFile}")
    private String pdfFontFile;
    @Value("${inputFile}")
    private String inputFile;
    @Value("${outputFile}")
    private String outputFile;
    @Value("${targetImage.url}")
    private String targetImageUrl;
    @Value("${yudao.oss.endpoint}")
    private String ossEndpoint;
    @Value("${yudao.oss.access-key}")
    private String ossAccessKey;
    @Value("${yudao.oss.secret-key}")
    private String ossSecretKey;
    @Value("${yudao.oss.bucket-name}")
    private String ossBucketName;
    private static final String formPdf = "安全作业票模版(表单)";
    private static final String formOutputPdf = "安全作业票模版(表单生成)";

    private static final String KEY_LICENCE_PRE = "KEY_LICENCE";
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final HashMap<Integer, String> LICENCE_TYPE_MAP = new HashMap<Integer, String>() {
        {
            put(1, "HOT");
            put(2, "RESTRICTED");
            put(3, "BLIND");
            put(4, "HEIGHT");
            put(5, "HOISTING");
            put(6, "TEMPORARY");
            put(7, "GROUNDBREAKING");
            put(8, "BREAK");
        }
    };
    private static final HashMap<Integer, String> LICENCE_NAME_MAP = new HashMap<Integer, String>() {
        {
            put(1, "动火");
            put(2, "受限空间");
            put(3, "盲板抽堵");
            put(4, "高处");
            put(5, "吊装");
            put(6, "临时用电");
            put(7, "动土");
            put(8, "断路");
        }
    };

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createLicence(Long userId, BizLicenceCreateReqVO createReqVO) {

        AdminUserDO user = userMapper.selectById(userId);
        createReqVO.setDeptId(user.getDeptId().toString());
        String number = getIncrementValue(KEY_LICENCE_PRE + LICENCE_TYPE_MAP.get(createReqVO.getType()));
        createReqVO.setNumber(number);
        // 保存草稿还是提交审核
        if (createReqVO.getSubmit() == null) {
            throw exception(ErrorCodeConstants.LICENCE_SUBMIT_IS_NULL);
        }
        Boolean submit = createReqVO.getSubmit();

        // 1、作业票主表
        BizLicenceDO licence = BizLicenceConvert.INSTANCE.convert(createReqVO);
        licenceMapper.insert(licence.setUserId(userId).setStatus(submit ? 2 : 1));
        // 2、分析数据表
        if (createReqVO.getAnalyzeDataList() != null && !createReqVO.getAnalyzeDataList().isEmpty()) {
            createReqVO.getAnalyzeDataList().forEach(p -> p.setLicenceId(licence.getId()));
            licenceAnalyzeDataMapper.insertBatch(createReqVO.getAnalyzeDataList());
        }
        // 3、安全措施
        if (createReqVO.getSafeMeasuresList() != null && !createReqVO.getSafeMeasuresList().isEmpty()) {
            createReqVO.getSafeMeasuresList().forEach(p -> p.setLicenceId(licence.getId()));
            licenceSafeMeasuresMapper.insertBatch(createReqVO.getSafeMeasuresList());
        }
        // 4、作业人员
        if (createReqVO.getPersonList() != null && !createReqVO.getPersonList().isEmpty()) {
            createReqVO.getPersonList().forEach(p -> p.setLicenceId(licence.getId()));
            bizLicencePersonMapper.insertBatch(createReqVO.getPersonList());
        }
        // 5、审核人员表
        // 动火
        int status = submit ? 0 : -1;
        if (createReqVO.getType() == 1) {
            //动火级别 二级、一级、特级
            String level = createReqVO.getLevel().toString();
            if (StringUtils.isEmpty(level)) {
                throw exception(ErrorCodeConstants.LICENCE_HOT_LEVEL_IS_NULL);
            }
            List<BizLicenceAuditDO> auditList = new ArrayList<>();
            BizLicenceAuditDO bizLicenceAuditLicensor = BizLicenceAuditDO.of(1, licence.getId(), licence.getLicensorId(), status, Boolean.FALSE, licence.getLicensor());
            BizLicenceAuditDO bizLicenceAuditSinger = BizLicenceAuditDO.of(2, licence.getId(), licence.getSignerId(), -1, Boolean.FALSE, licence.getSigner());
            auditList.add(bizLicenceAuditLicensor);
            auditList.add(bizLicenceAuditSinger);
            switch (level) {
                // 二级动火
                case "1":
                    bizLicenceAuditSinger.setLastUser(Boolean.TRUE);
                    break;
                // 一级动火
                case "2":
                    BizLicenceAuditDO bizLicenceAuditInCharge = BizLicenceAuditDO.of(3, licence.getId(), licence.getInChargeId(), -1, Boolean.TRUE, licence.getInCharge());
                    auditList.add(bizLicenceAuditInCharge);
                    break;
                // 特殊动火
                case "3":
                    BizLicenceAuditDO bizLicenceAuditInCharge2 = BizLicenceAuditDO.of(3, licence.getId(), licence.getInChargeId(), -1, Boolean.TRUE, licence.getInCharge());
                    BizLicenceAuditDO bizLicenceAuditMainInCharge = BizLicenceAuditDO.of(4, licence.getId(), licence.getMainInChargeId(), -1, Boolean.FALSE, licence.getMainInCharge());
                    auditList.add(bizLicenceAuditInCharge2);
                    auditList.add(bizLicenceAuditMainInCharge);
                    break;
                default:
            }
            licenceAuditMapper.insertBatch(auditList);

        } else {
            // 除动火外的其他种类
            List<BizLicenceAuditDO> auditList = new ArrayList<>();
            BizLicenceAuditDO bizLicenceAuditLicensor = BizLicenceAuditDO.of(1, licence.getId(), licence.getLicensorId(), status, Boolean.FALSE, licence.getLicensor());
            BizLicenceAuditDO bizLicenceAuditSinger = BizLicenceAuditDO.of(2, licence.getId(), licence.getSignerId(), -1, Boolean.TRUE, licence.getSigner());
            auditList.add(bizLicenceAuditLicensor);
            auditList.add(bizLicenceAuditSinger);
            licenceAuditMapper.insertBatch(auditList);
        }
        return licence.getId();
    }

    // redis编号自增
    private String getIncrementValue(String preKey) {
        String currentDate = SequenceUtil.getCurrentDate();
        String key = preKey + currentDate;
        long sequence = stringRedisTemplate.opsForValue().increment(key);
        String seq = SequenceUtil.getSequence(sequence);
        return currentDate + seq;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateLicence(BizLicenceUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateLicenceExists(updateReqVO.getId());
        // 保存草稿还是提交审核
        if (updateReqVO.getSubmit() == null) {
            throw exception(ErrorCodeConstants.LICENCE_SUBMIT_IS_NULL);
        }
        Boolean submit = updateReqVO.getSubmit();

        // 1、作业票主表
        BizLicenceDO licence = BizLicenceConvert.INSTANCE.convert(updateReqVO);
        licenceMapper.updateById(licence.setStatus(submit ? 2 : 1));
        // 2、分析数据表
        if (updateReqVO.getAnalyzeDataList() != null && !updateReqVO.getAnalyzeDataList().isEmpty()) {
            Map<String, Object> analyzeMap = new HashMap<>(8);
            analyzeMap.put("licence_id", updateReqVO.getId());
            licenceAnalyzeDataMapper.deleteByMap(analyzeMap);
            updateReqVO.getAnalyzeDataList().forEach(p -> p.setLicenceId(licence.getId()));
            licenceAnalyzeDataMapper.insertBatch(updateReqVO.getAnalyzeDataList());
        }
        // 3、安全措施
        if (updateReqVO.getSafeMeasuresList() != null && !updateReqVO.getSafeMeasuresList().isEmpty()) {
            Map<String, Object> measuresMap = new HashMap<>(8);
            measuresMap.put("licence_id", updateReqVO.getId());
            licenceSafeMeasuresMapper.deleteByMap(measuresMap);
            updateReqVO.getSafeMeasuresList().forEach(p -> p.setLicenceId(licence.getId()));
            licenceSafeMeasuresMapper.insertBatch(updateReqVO.getSafeMeasuresList());
        }
        // 4、作业人员
        if (updateReqVO.getPersonList() != null && !updateReqVO.getPersonList().isEmpty()) {
            Map<String, Object> personMap = new HashMap<>(8);
            personMap.put("licence_id", updateReqVO.getId());
            bizLicencePersonMapper.deleteByMap(personMap);
            updateReqVO.getPersonList().forEach(p -> p.setLicenceId(licence.getId()));
            bizLicencePersonMapper.insertBatch(updateReqVO.getPersonList());
        }
        // 5、审核人员表
        Map<String, Object> analyzeMap = new HashMap<>(8);
        analyzeMap.put("licence_id", updateReqVO.getId());
        licenceAuditMapper.deleteByMap(analyzeMap);
        // 动火
        int status = submit ? 0 : -1;
        if (updateReqVO.getType() == 1) {

            //动火级别 二级、一级、特级
            String level = updateReqVO.getLevel().toString();
            if (StringUtils.isEmpty(level)) {
                throw exception(ErrorCodeConstants.LICENCE_HOT_LEVEL_IS_NULL);
            }
            List<BizLicenceAuditDO> auditList = new ArrayList<>();
            BizLicenceAuditDO bizLicenceAuditLicensor = BizLicenceAuditDO.of(1, licence.getId(), licence.getLicensorId(), status, Boolean.FALSE, licence.getLicensor());
            BizLicenceAuditDO bizLicenceAuditSinger = BizLicenceAuditDO.of(2, licence.getId(), licence.getSignerId(), -1, Boolean.FALSE, licence.getSigner());
            auditList.add(bizLicenceAuditLicensor);
            auditList.add(bizLicenceAuditSinger);
            switch (level) {
                // 二级动火
                case "1":
                    bizLicenceAuditSinger.setLastUser(Boolean.TRUE);
                    break;
                // 一级动火
                case "2":
                    BizLicenceAuditDO bizLicenceAuditInCharge = BizLicenceAuditDO.of(3, licence.getId(), licence.getInChargeId(), -1, Boolean.TRUE, licence.getInCharge());
                    auditList.add(bizLicenceAuditInCharge);
                    break;
                // 特殊动火
                case "3":
                    BizLicenceAuditDO bizLicenceAuditInCharge2 = BizLicenceAuditDO.of(3, licence.getId(), licence.getInChargeId(), -1, Boolean.TRUE, licence.getInCharge());
                    BizLicenceAuditDO bizLicenceAuditMainInCharge = BizLicenceAuditDO.of(4, licence.getId(), licence.getMainInChargeId(), -1, Boolean.FALSE, licence.getMainInCharge());
                    auditList.add(bizLicenceAuditInCharge2);
                    auditList.add(bizLicenceAuditMainInCharge);
                    break;
                default:
            }
            licenceAuditMapper.insertBatch(auditList);
        } else {
            // 除动火外的其他种类
            List<BizLicenceAuditDO> auditList = new ArrayList<>();
            BizLicenceAuditDO bizLicenceAuditLicensor = BizLicenceAuditDO.of(1, licence.getId(), licence.getLicensorId(), status, Boolean.FALSE, licence.getLicensor());
            BizLicenceAuditDO bizLicenceAuditSinger = BizLicenceAuditDO.of(2, licence.getId(), licence.getSignerId(), -1, Boolean.TRUE, licence.getSigner());
            auditList.add(bizLicenceAuditLicensor);
            auditList.add(bizLicenceAuditSinger);
            licenceAuditMapper.insertBatch(auditList);
        }
    }

    @Override
    public String submit(String licenceId) {
        if (StringUtils.isEmpty(licenceId)) {
            throw exception(ErrorCodeConstants.LICENCE_ID_IS_NULL);
        }
        BizLicenceDO licenceDO = licenceMapper.selectById(licenceId);
        if (licenceDO == null) {
            throw exception(ErrorCodeConstants.LICENCE_ID_IS_ERROR);
        }
        licenceDO.setStatus(2);
        licenceMapper.updateById(licenceDO);
        // 5、审核人员表
        Map<String, Object> analyzeMap = new HashMap<>(8);
        analyzeMap.put("licence_id", licenceId);
        licenceAuditMapper.deleteByMap(analyzeMap);
        // 动火
        int status = 0;
        if (licenceDO.getType() == 1) {
            //动火级别 二级、一级、特级
            String level = licenceDO.getLevel().toString();
            if (StringUtils.isEmpty(level)) {
                throw exception(ErrorCodeConstants.LICENCE_HOT_LEVEL_IS_NULL);
            }
            List<BizLicenceAuditDO> auditList = new ArrayList<>();
            BizLicenceAuditDO bizLicenceAuditLicensor = BizLicenceAuditDO.of(1, licenceDO.getId(), licenceDO.getLicensorId(), status, Boolean.FALSE, licenceDO.getLicensor());
            BizLicenceAuditDO bizLicenceAuditSinger = BizLicenceAuditDO.of(2, licenceDO.getId(), licenceDO.getSignerId(), -1, Boolean.FALSE, licenceDO.getSigner());
            auditList.add(bizLicenceAuditLicensor);
            auditList.add(bizLicenceAuditSinger);
            switch (level) {
                // 二级动火
                case "1":
                    bizLicenceAuditSinger.setLastUser(Boolean.TRUE);
                    break;
                // 一级动火
                case "2":
                    BizLicenceAuditDO bizLicenceAuditInCharge = BizLicenceAuditDO.of(3, licenceDO.getId(), licenceDO.getInChargeId(), -1, Boolean.TRUE, licenceDO.getInCharge());
                    auditList.add(bizLicenceAuditInCharge);
                    break;
                // 特殊动火
                case "3":
                    BizLicenceAuditDO bizLicenceAuditInCharge2 = BizLicenceAuditDO.of(3, licenceDO.getId(), licenceDO.getInChargeId(), -1, Boolean.TRUE, licenceDO.getInCharge());
                    BizLicenceAuditDO bizLicenceAuditMainInCharge = BizLicenceAuditDO.of(4, licenceDO.getId(), licenceDO.getMainInChargeId(), -1, Boolean.FALSE, licenceDO.getMainInCharge());
                    auditList.add(bizLicenceAuditInCharge2);
                    auditList.add(bizLicenceAuditMainInCharge);
                    break;
                default:
            }
            licenceAuditMapper.insertBatch(auditList);
        } else {
            // 除动火外的其他种类
            List<BizLicenceAuditDO> auditList = new ArrayList<>();
            BizLicenceAuditDO bizLicenceAuditLicensor = BizLicenceAuditDO.of(1, licenceDO.getId(), licenceDO.getLicensorId(), status, Boolean.FALSE, licenceDO.getLicensor());
            BizLicenceAuditDO bizLicenceAuditSinger = BizLicenceAuditDO.of(2, licenceDO.getId(), licenceDO.getSignerId(), -1, Boolean.TRUE, licenceDO.getSigner());
            auditList.add(bizLicenceAuditLicensor);
            auditList.add(bizLicenceAuditSinger);
            licenceAuditMapper.insertBatch(auditList);
        }

        return licenceId;
    }

    @Override
    public void deleteLicence(String id) {
        // 校验存在
        this.validateLicenceExists(id);
        // 删除
        licenceMapper.deleteById(id);
    }

    private void validateLicenceExists(String id) {
        if (licenceMapper.selectById(id) == null) {
            throw exception(LICENCE_NOT_EXISTS);
        }
    }

    @Override
    public BizLicenceRespVO getLicence(String id) {
        if (StringUtils.isEmpty(id)) {
            throw exception(ErrorCodeConstants.LICENCE_ID_IS_NULL);
        }
        BizLicenceDO licenceDO = licenceMapper.selectById(id);
        if (licenceDO == null) {
            throw exception(ErrorCodeConstants.LICENCE_NOT_EXISTS);
        }
        BizLicenceRespVO licenceRespVO = BizLicenceConvert.INSTANCE.convert(licenceDO);
        // 分析数据
        List<BizLicenceAnalyzeDataDO> analyzeDataList = licenceAnalyzeDataMapper.selectList(new BizLicenceAnalyzeDataExportReqVO().setLicenceId(id));
        // 安全措施
        List<BizLicenceSafeMeasuresDO> safeMeasuresList = licenceSafeMeasuresMapper.selectList(new BizLicenceSafeMeasuresExportReqVO().setLicenceId(id));
        // 作业人员
        List<BizLicencePersonDO> personList = bizLicencePersonMapper.selectList(new BizLicencePersonExportReqVO().setLicenceId(id));
        licenceRespVO.setAnalyzeDataList(analyzeDataList);
        licenceRespVO.setSafeMeasuresList(safeMeasuresList);
        licenceRespVO.setPersonList(personList);
        return licenceRespVO;
    }

    @Override
    public List<BizLicenceRespVO> getLicenceList(Long userId, BizLicenceExportReqVO licenceExportReqVO) {
        List<BizLicenceRespVO> licenceList = BizLicenceConvert.INSTANCE.convertList(licenceMapper.selectList(licenceExportReqVO));

        if (licenceList.isEmpty()) {
            return licenceList;
        }


        List<String> licenceIds = licenceList.stream().map(BizLicenceRespVO::getId).collect(Collectors.toList());

        List<BizLicencePersonDO> personDOList = bizLicencePersonMapper.selectListInLicenceIds(licenceIds);
        Map<String, List<BizLicencePersonDO>> personMap = personDOList.stream().collect(Collectors.groupingBy(BizLicencePersonDO::getLicenceId));
        List<BizLicenceSafeMeasuresDO> measuresDOList = licenceSafeMeasuresMapper.selectListInLicenceIds(licenceIds);
        Map<String, List<BizLicenceSafeMeasuresDO>> measureMap = measuresDOList.stream().collect(Collectors.groupingBy(BizLicenceSafeMeasuresDO::getLicenceId));
        List<BizLicenceAnalyzeDataDO> analyzeDataDOList = licenceAnalyzeDataMapper.selectListInLicenceIds(licenceIds);
        Map<String, List<BizLicenceAnalyzeDataDO>> analyzeDataMap = analyzeDataDOList.stream().collect(Collectors.groupingBy(BizLicenceAnalyzeDataDO::getLicenceId));
        for (BizLicenceRespVO bizLicenceRespVO : licenceList) {
            bizLicenceRespVO.setSafeMeasuresList(measureMap.get(bizLicenceRespVO.getId()));
            bizLicenceRespVO.setAnalyzeDataList(analyzeDataMap.get(bizLicenceRespVO.getId()));
            bizLicenceRespVO.setPersonList(personMap.get(bizLicenceRespVO.getId()));
        }
        return licenceList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean auditLicence(Long userId, BizLicenceAuditVO auditVO) {
        // 获取该作业票的相关审核人员
        List<BizLicenceAuditDO> auditDOList = licenceAuditMapper.selectList(new BizLicenceAuditExportReqVO().setLicenceId(auditVO.getLicenceId()));
        if (auditDOList.isEmpty()) {
            throw exception(ErrorCodeConstants.LICENCE_ID_IS_ERROR);
        }
        List<BizLicenceAuditDO> concurrentAuditDOList = auditDOList.stream().filter(p ->
                Objects.equals(p.getAuditUserId(), String.valueOf(userId)) && p.getStatus() == 0
        ).collect(Collectors.toList());
        if (concurrentAuditDOList.isEmpty()) {
            throw exception(ErrorCodeConstants.CONCURRENT_USER_IS_NOT_AUDIT);
        }
        BizLicenceAuditDO licenceAuditDO = concurrentAuditDOList.get(0);


        BizLicenceDO licenceDO = licenceMapper.selectById(auditVO.getLicenceId());
        // 如果选择驳回
        if (!auditVO.getSubmit()) {
            licenceAuditDO.setStatus(2);
            licenceAuditMapper.updateById(licenceAuditDO);

            licenceDO.setStatus(4);
            licenceDO.setReasonOfReject(auditVO.getReasonForRejection());
            licenceMapper.updateById(licenceDO);
            return licenceAuditDO.getLastUser() ? Boolean.TRUE : Boolean.FALSE;
        }
        // 审核通过
        licenceAuditDO.setStatus(1);
        licenceAuditMapper.updateById(licenceAuditDO);
        // 最终审核用户
        if (licenceAuditDO.getLastUser()) {
            licenceDO.setStatus(3);
            licenceMapper.updateById(licenceDO);
            return Boolean.TRUE;
        } else {
            Integer concurrentNumber = licenceAuditDO.getNumber();
            List<BizLicenceAuditDO> nextAuditDOList = auditDOList.stream().filter(p -> Objects.equals(p.getNumber(), concurrentNumber + 1)).collect(Collectors.toList());
            BizLicenceAuditDO nextAudit = nextAuditDOList.get(0);
            nextAudit.setStatus(0);
            licenceAuditMapper.updateById(nextAudit);
            return Boolean.FALSE;
        }
    }

    @Override
    public PageResult<BizLicenceRespVO> getLicencePage(Long userId, BizLicencePageReqVO pageReqVO) {
        PageResult<BizLicenceDO> pageResult = licenceMapper.selectPage(userId, pageReqVO);
        List<BizLicenceRespVO> licenceList = BizLicenceConvert.INSTANCE.convertList(pageResult.getList());
        if (licenceList.isEmpty()) {
            return PageResult.empty();
        }

        List<String> licenceIds = licenceList.stream().map(BizLicenceRespVO::getId).collect(Collectors.toList());

        List<BizLicencePersonDO> personDOList = bizLicencePersonMapper.selectListInLicenceIds(licenceIds);
        Map<String, List<BizLicencePersonDO>> personMap = personDOList.stream().collect(Collectors.groupingBy(BizLicencePersonDO::getLicenceId));
        List<BizLicenceSafeMeasuresDO> measuresDOList = licenceSafeMeasuresMapper.selectListInLicenceIds(licenceIds);
        Map<String, List<BizLicenceSafeMeasuresDO>> measureMap = measuresDOList.stream().collect(Collectors.groupingBy(BizLicenceSafeMeasuresDO::getLicenceId));
        List<BizLicenceAnalyzeDataDO> analyzeDataDOList = licenceAnalyzeDataMapper.selectListInLicenceIds(licenceIds);
        Map<String, List<BizLicenceAnalyzeDataDO>> analyzeDataMap = analyzeDataDOList.stream().collect(Collectors.groupingBy(BizLicenceAnalyzeDataDO::getLicenceId));
        for (BizLicenceRespVO bizLicenceRespVO : licenceList) {
            bizLicenceRespVO.setSafeMeasuresList(measureMap.get(bizLicenceRespVO.getId()));
            bizLicenceRespVO.setAnalyzeDataList(analyzeDataMap.get(bizLicenceRespVO.getId()));
            bizLicenceRespVO.setPersonList(personMap.get(bizLicenceRespVO.getId()));
        }
        return BizLicenceConvert.INSTANCE.convertPage(pageResult).setList(licenceList);
    }

    @Override
    public List<BizLicenceRespVO> getTodoList(Long userId) {
        List<BizLicenceAuditDO> auditDOList = licenceAuditMapper.selectList(new BizLicenceAuditExportReqVO().setAuditUserId(String.valueOf(userId)));
        if (auditDOList == null || auditDOList.isEmpty()) {
            return Collections.emptyList();
        }
        // 需要当前用户审核的
        List<BizLicenceAuditDO> todoList = auditDOList.stream().filter(p -> Objects.equals(p.getStatus(), 0)).collect(Collectors.toList());
        if (todoList.isEmpty()) {
            return Collections.emptyList();
        }
        List<String> licenceIds = todoList.stream().map(BizLicenceAuditDO::getLicenceId).collect(Collectors.toList());

        List<BizLicenceRespVO> licenceList = getLicenceList(licenceIds);
        // 安全措施
        List<BizLicenceSafeMeasuresDO> measuresDOList = licenceSafeMeasuresMapper.selectListInLicenceIds(licenceIds);
        Map<String, List<BizLicenceSafeMeasuresDO>> measureMap = measuresDOList.stream().collect(Collectors.groupingBy(BizLicenceSafeMeasuresDO::getLicenceId));
        // 分析数据
        List<BizLicenceAnalyzeDataDO> analyzeDataDOList = licenceAnalyzeDataMapper.selectListInLicenceIds(licenceIds);
        Map<String, List<BizLicenceAnalyzeDataDO>> analyzeDataMap = analyzeDataDOList.stream().collect(Collectors.groupingBy(BizLicenceAnalyzeDataDO::getLicenceId));
        for (BizLicenceRespVO bizLicenceRespVO : licenceList) {
            bizLicenceRespVO.setSafeMeasuresList(measureMap.get(bizLicenceRespVO.getId()));
            bizLicenceRespVO.setAnalyzeDataList(analyzeDataMap.get(bizLicenceRespVO.getId()));
        }

        return licenceList;
    }

    private List<BizLicenceRespVO> getLicenceList(List<String> licenceIds) {
        return BizLicenceConvert.INSTANCE.convertList(licenceMapper.selectListInLicenceIds(licenceIds));
    }

    @Override
    public List<BizLicenceAuditRespVO> getLicenceAuditList(String licenceId) {
        return BizLicenceAuditConvert.INSTANCE.convertList(licenceAuditMapper.selectList(new BizLicenceAuditExportReqVO().setLicenceId(licenceId)));
    }

    @Override
    public PrintPdfVO printPdf(String licenceId) {
        BizLicenceRespVO bizLicenceRespVO = getLicence(licenceId);
        return fillPdf(bizLicenceRespVO);

    }

    PrintPdfVO fillPdf(BizLicenceRespVO bizLicenceRespVO) {
        PrintPdfVO printPdfVO = new PrintPdfVO();
        OutputStream os = null;
        PdfStamper ps = null;
        PdfReader reader = null;

        String inputUrl = inputFile + LICENCE_NAME_MAP.get(bizLicenceRespVO.getType()) + formPdf + ".pdf";
        String outPutFile = outputFile + LICENCE_NAME_MAP.get(bizLicenceRespVO.getType()) + formOutputPdf + bizLicenceRespVO.getId() + ".pdf";
        try {
            os = new FileOutputStream(outPutFile);
            // 2 读入pdf表单
            reader = new PdfReader(inputUrl);
            // 3 根据表单生成一个新的pdf
            ps = new PdfStamper(reader, os);
            // 4 获取pdf表单
            AcroFields form = ps.getAcroFields();
            // 5给表单添加中文字体
            BaseFont bf = BaseFont.createFont(pdfFontFile, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            form.addSubstitutionFont(bf);
            // 6查询数据================================================
            Map<String, Object> data = getHotData(bizLicenceRespVO);
            // 7遍历data 给pdf表单表格赋值
            for (String key : data.keySet()) {
                if (data.get(key) != null) {
                    form.setField(key, data.get(key).toString());
                }
            }
            ps.setFormFlattening(true);

            // 安全措施
            List<BizLicenceSafeMeasuresDO> safeMeasures = bizLicenceRespVO.getSafeMeasuresList();
            int measureLength = 0;
            int j = 2;
            if (!safeMeasures.isEmpty()) {
                for (BizLicenceSafeMeasuresDO safeMeasure : safeMeasures) {
                    if (StringUtils.isNotEmpty(safeMeasure.getPhoto())) {
                        manipulatePdf(reader, safeMeasure.getPhoto(), "第" + (j - 1) + "条安全措施检查照片", ps, j, bf);
                        j++;
                    }
                }
            }
            measureLength = measureLength + j;

            // 作业人
            List<BizLicencePersonDO> persons = bizLicenceRespVO.getPersonList();
            if (!persons.isEmpty()) {
                ps.insertPage(measureLength, reader.getPageSizeWithRotation(1));
                for (int i = 0; i < persons.size(); i++) {
                    if (StringUtils.isNotEmpty(persons.get(i).getCertification())) {
                        manipulatePersonPdf(measureLength, persons.get(i).getCertification(), ps, i, bf);
                    }
                }
                measureLength++;
            }
            // 分析数据
            List<BizLicenceAnalyzeDataDO> analyzeDatas = bizLicenceRespVO.getAnalyzeDataList();
            if (!analyzeDatas.isEmpty()) {
                for (int i = 0; i < analyzeDatas.size(); i++) {
                    if (StringUtils.isNotEmpty(analyzeDatas.get(i).getPhoto())) {
                        manipulatePdf(reader, analyzeDatas.get(i).getPhoto(), "第" + (i + 1) + "条分析数据照片", ps, measureLength++, bf);
                    }
                }
            }
            // 监护人
            if (StringUtils.isNotEmpty(bizLicenceRespVO.getGuardian())) {
                addImageToPdf(form, ps, bizLicenceRespVO.getGuardian(), "guardian");
            }
            // 签章嵌入表单
            if (StringUtils.isNotEmpty(bizLicenceRespVO.getSignerSignature())) {
                addImageToPdf(form, ps, bizLicenceRespVO.getSignerSignature(), "signer");
            }
            if (StringUtils.isNotEmpty(bizLicenceRespVO.getLicensorSignature())) {
                addImageToPdf(form, ps, bizLicenceRespVO.getLicensorSignature(), "licensor");
            }
            if (StringUtils.isNotEmpty(bizLicenceRespVO.getMainInChargeSignature())) {
                addImageToPdf(form, ps, bizLicenceRespVO.getMainInChargeSignature(), "mainInChargeSignature");
            }
            if (StringUtils.isNotEmpty(bizLicenceRespVO.getInChargeSignature())) {
                addImageToPdf(form, ps, bizLicenceRespVO.getInChargeSignature(), "inChargeSignature");
            }

            printPdfVO.setFilepath(outPutFile);
            printPdfVO.setOssEndpoint(ossEndpoint);
            printPdfVO.setOssBucketName(ossBucketName);
            printPdfVO.setOssSecretKey(ossSecretKey);
            printPdfVO.setOssAccessKey(ossAccessKey);
            printPdfVO.setTargetPath(DateUtils.datePath() + "/" + bizLicenceRespVO.getId() + ".pdf");

            System.out.println("===============PDF导出成功=============");
        } catch (Exception e) {
            System.out.println("===============PDF导出失败=============");
            e.printStackTrace();
        } finally {
            try {
                ps.close();
                reader.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return printPdfVO;
    }


    // 动火数据
    private Map<String, Object> getHotData(BizLicenceRespVO bizLicenceRespVO) {
        Map<String, Object> map = new HashMap<>();
        map.put("applicationUnit", bizLicenceRespVO.getApplicationUnit());
        map.put("applicant", bizLicenceRespVO.getApplicant());
        map.put("createTime", sdf.format(bizLicenceRespVO.getCreateTime()));
        map.put("content", bizLicenceRespVO.getContent());
        map.put("address", bizLicenceRespVO.getAddress());
        map.put("level", bizLicenceRespVO.getLevel());
        map.put("way", bizLicenceRespVO.getWay());
        map.put("startTime", sdf.format(bizLicenceRespVO.getStartTime()));
        map.put("endTime", sdf.format(bizLicenceRespVO.getEndTime()));

        List<BizLicenceAnalyzeDataDO> analyzeDataDOList = bizLicenceRespVO.getAnalyzeDataList();
        if (analyzeDataDOList != null && !analyzeDataDOList.isEmpty()) {
            for (int i = 1; i <= analyzeDataDOList.size(); i++) {
                map.put("analyzeTime" + i, sdf.format(analyzeDataDOList.get(i - 1).getCreateTime()));
                map.put("analyzePoint" + i, analyzeDataDOList.get(i - 1).getAnalyzePoint());
                map.put("analyzeData" + i, analyzeDataDOList.get(i - 1).getAnalyzeData());
                map.put("analyst" + i, analyzeDataDOList.get(i - 1).getAnalyst());
            }
        }
        if (bizLicenceRespVO.getPersonList() != null && !bizLicenceRespVO.getPersonList().isEmpty()) {
            List<String> personNames = bizLicenceRespVO.getPersonList().stream().map(BizLicencePersonDO::getWorkerName).collect(Collectors.toList());
            String persons = String.join(",", personNames);
            map.put("persons", persons);
        }

        map.put("other_licence_name", bizLicenceRespVO.getOtherLicenceName());
        map.put("other_licence_number", bizLicenceRespVO.getOtherLicenceId());
        map.put("fill_54", bizLicenceRespVO.getIdentificationResult());
        map.put("licence_number", bizLicenceRespVO.getNumber());

        List<BizLicenceSafeMeasuresDO> measuresDOList = bizLicenceRespVO.getSafeMeasuresList();
        if (measuresDOList != null && !measuresDOList.isEmpty()) {
            for (int i = 1; i <= measuresDOList.size(); i++) {
                map.put("mearsureContent" + i, measuresDOList.get(i - 1).getContent());
                if (measuresDOList.get(i - 1).getApplicable() != null) {
                    map.put("applicable" + i, measuresDOList.get(i - 1).getApplicable() ? "是" : "否");
                }
                if (measuresDOList.get(i - 1).getQualified() != null) {
                    map.put("qualified" + i, measuresDOList.get(i - 1).getQualified() ? "是" : "否");
                }
            }
        }
        return map;
    }

    // 受限空间数据
    private Map<String, Object> getConfinedSpace(BizLicenceRespVO bizLicenceRespVO) {
        Map<String, Object> map = new HashMap<>();
        map.put("applicationUnit", bizLicenceRespVO.getApplicationUnit());
        map.put("applicant", bizLicenceRespVO.getApplicant());
        map.put("createTime", sdf.format(bizLicenceRespVO.getCreateTime()));
        map.put("name", bizLicenceRespVO.getName());
        map.put("originalMedium", bizLicenceRespVO.getOriginalMedium());
        map.put("guardian", bizLicenceRespVO.getGuardian());
        map.put("startTime", sdf.format(bizLicenceRespVO.getStartTime()));
        map.put("endTime", sdf.format(bizLicenceRespVO.getEndTime()));

        map.put("other_licence_name", bizLicenceRespVO.getOtherLicenceName());
        map.put("other_licence_number", bizLicenceRespVO.getOtherLicenceId());
        map.put("fill_54", bizLicenceRespVO.getIdentificationResult());
        map.put("licence_number", bizLicenceRespVO.getNumber());

        if (bizLicenceRespVO.getPersonList() != null && !bizLicenceRespVO.getPersonList().isEmpty()) {
            List<String> personNames = bizLicenceRespVO.getPersonList().stream().map(BizLicencePersonDO::getWorkerName).collect(Collectors.toList());
            String persons = String.join(",", personNames);
            map.put("persons", persons);
        }

        List<BizLicenceAnalyzeDataDO> analyzeDataDOList = bizLicenceRespVO.getAnalyzeDataList();
        if (analyzeDataDOList != null && !analyzeDataDOList.isEmpty()) {
            for (int i = 1; i <= analyzeDataDOList.size(); i++) {
                map.put("analyzeTime" + i, sdf.format(analyzeDataDOList.get(i - 1).getCreateTime()));
                map.put("analyzePoint" + i, analyzeDataDOList.get(i - 1).getAnalyzePoint());
                map.put("analyzeData" + i, analyzeDataDOList.get(i - 1).getAnalyzeData());
                map.put("analyst" + i, analyzeDataDOList.get(i - 1).getAnalyst());
                map.put("toxicGas" + i, analyzeDataDOList.get(i).getToxicGas());
                map.put("combustible" + i, analyzeDataDOList.get(i).getCombustible());
                map.put("oxygen" + i, analyzeDataDOList.get(i).getOxygen());
            }
        }

        List<BizLicenceSafeMeasuresDO> measuresDOList = bizLicenceRespVO.getSafeMeasuresList();
        if (measuresDOList != null && !measuresDOList.isEmpty()) {
            for (int i = 1; i <= measuresDOList.size(); i++) {
                map.put("mearsureContent" + i, measuresDOList.get(i - 1).getContent());
                map.put("applicable" + i, measuresDOList.get(i - 1).getApplicable() ? "是" : "否");
                map.put("qualified" + i, measuresDOList.get(i - 1).getQualified() ? "是" : "否");
            }
        }
        return map;

    }

    // 吊装
    public Map<String, Object> getHoistingData(BizLicenceRespVO bizLicenceRespVO) {
        Map<String, Object> map = new HashMap<>();
        map.put("address", bizLicenceRespVO.getAddress());
        map.put("liftingTools", bizLicenceRespVO.getLiftingTools());
        map.put("createTime", sdf.format(bizLicenceRespVO.getCreateTime()));
        map.put("personnelNumber", bizLicenceRespVO.getPersonnelNumber());
        map.put("commandNumber", bizLicenceRespVO.getCommandNumber());
        map.put("startTime", sdf.format(bizLicenceRespVO.getStartTime()));
        map.put("endTime", sdf.format(bizLicenceRespVO.getEndTime()));

        map.put("other_licence_name", bizLicenceRespVO.getOtherLicenceName());
        map.put("other_licence_number", bizLicenceRespVO.getOtherLicenceId());
        map.put("fill_54", bizLicenceRespVO.getIdentificationResult());
        map.put("licence_number", bizLicenceRespVO.getNumber());
        map.put("liftingWeight", bizLicenceRespVO.getLiftingWeight());
        map.put("content", bizLicenceRespVO.getContent());

        if (bizLicenceRespVO.getPersonList() != null && !bizLicenceRespVO.getPersonList().isEmpty()) {
            List<String> personNames = bizLicenceRespVO.getPersonList().stream().map(BizLicencePersonDO::getWorkerName).collect(Collectors.toList());
            String persons = String.join(",", personNames);
            map.put("persons", persons);
        }


        List<BizLicenceSafeMeasuresDO> measuresDOList = bizLicenceRespVO.getSafeMeasuresList();
        if (measuresDOList != null && !measuresDOList.isEmpty()) {
            for (int i = 1; i <= measuresDOList.size(); i++) {
                map.put("mearsureContent" + i, measuresDOList.get(i - 1).getContent());
                map.put("applicable" + i, measuresDOList.get(i - 1).getApplicable() ? "是" : "否");
                map.put("qualified" + i, measuresDOList.get(i - 1).getQualified() ? "是" : "否");
            }
        }
        return map;
    }

    // 动土
    public Map<String, Object> getGroundBreaking(BizLicenceRespVO bizLicenceRespVO) {
        Map<String, Object> map = new HashMap<>();
        map.put("applicationUnit", bizLicenceRespVO.getApplicationUnit());
        map.put("applicant", bizLicenceRespVO.getApplicant());
        map.put("createTime", sdf.format(bizLicenceRespVO.getCreateTime()));
        map.put("address", bizLicenceRespVO.getAddress());
        map.put("originalMedium", bizLicenceRespVO.getOriginalMedium());
        map.put("guardian", bizLicenceRespVO.getGuardian());
        map.put("startTime", sdf.format(bizLicenceRespVO.getStartTime()));
        map.put("endTime", sdf.format(bizLicenceRespVO.getEndTime()));

        map.put("other_licence_name", bizLicenceRespVO.getOtherLicenceName());
        map.put("other_licence_number", bizLicenceRespVO.getOtherLicenceId());
        map.put("fill_54", bizLicenceRespVO.getIdentificationResult());
        map.put("licence_number", bizLicenceRespVO.getNumber());

        if (bizLicenceRespVO.getPersonList() != null && !bizLicenceRespVO.getPersonList().isEmpty()) {
            List<String> personNames = bizLicenceRespVO.getPersonList().stream().map(BizLicencePersonDO::getWorkerName).collect(Collectors.toList());
            String persons = String.join(",", personNames);
            map.put("persons", persons);
        }


        List<BizLicenceSafeMeasuresDO> measuresDOList = bizLicenceRespVO.getSafeMeasuresList();
        if (measuresDOList != null && !measuresDOList.isEmpty()) {
            for (int i = 1; i <= measuresDOList.size(); i++) {
                map.put("mearsureContent" + i, measuresDOList.get(i - 1).getContent());
                map.put("applicable" + i, measuresDOList.get(i - 1).getApplicable() ? "是" : "否");
                map.put("qualified" + i, measuresDOList.get(i - 1).getQualified() ? "是" : "否");
            }
        }
        return map;
    }

    // 断路
    public Map<String,Object> getOpenCircuit(BizLicenceRespVO bizLicenceRespVO){
        Map<String, Object> map = new HashMap<>();
        map.put("applicationUnit", bizLicenceRespVO.getApplicationUnit());
        map.put("applicant", bizLicenceRespVO.getApplicant());
        map.put("createTime", sdf.format(bizLicenceRespVO.getCreateTime()));
        map.put("address", bizLicenceRespVO.getAddress());
        map.put("originalMedium", bizLicenceRespVO.getOriginalMedium());
        map.put("guardian", bizLicenceRespVO.getGuardian());
        map.put("startTime", sdf.format(bizLicenceRespVO.getStartTime()));
        map.put("endTime", sdf.format(bizLicenceRespVO.getEndTime()));

        map.put("other_licence_name", bizLicenceRespVO.getOtherLicenceName());
        map.put("other_licence_number", bizLicenceRespVO.getOtherLicenceId());
        map.put("fill_54", bizLicenceRespVO.getIdentificationResult());
        map.put("licence_number", bizLicenceRespVO.getNumber());

        if (bizLicenceRespVO.getPersonList() != null && !bizLicenceRespVO.getPersonList().isEmpty()) {
            List<String> personNames = bizLicenceRespVO.getPersonList().stream().map(BizLicencePersonDO::getWorkerName).collect(Collectors.toList());
            String persons = String.join(",", personNames);
            map.put("persons", persons);
        }

        List<BizLicenceSafeMeasuresDO> measuresDOList = bizLicenceRespVO.getSafeMeasuresList();
        if (measuresDOList != null && !measuresDOList.isEmpty()) {
            for (int i = 1; i <= measuresDOList.size(); i++) {
                map.put("mearsureContent" + i, measuresDOList.get(i - 1).getContent());
                map.put("applicable" + i, measuresDOList.get(i - 1).getApplicable() ? "是" : "否");
                map.put("qualified" + i, measuresDOList.get(i - 1).getQualified() ? "是" : "否");
            }
        }
        return map;
    }

    // 高处
    public Map<String,Object> getHighPlace(BizLicenceRespVO bizLicenceRespVO){
        Map<String, Object> map = new HashMap<>();
        map.put("applicationUnit", bizLicenceRespVO.getApplicationUnit());
        map.put("applicant", bizLicenceRespVO.getApplicant());
        map.put("createTime", sdf.format(bizLicenceRespVO.getCreateTime()));
        map.put("address", bizLicenceRespVO.getAddress());
        map.put("originalMedium", bizLicenceRespVO.getOriginalMedium());
        map.put("guardian", bizLicenceRespVO.getGuardian());
        map.put("startTime", sdf.format(bizLicenceRespVO.getStartTime()));
        map.put("endTime", sdf.format(bizLicenceRespVO.getEndTime()));

        map.put("other_licence_name", bizLicenceRespVO.getOtherLicenceName());
        map.put("other_licence_number", bizLicenceRespVO.getOtherLicenceId());
        map.put("fill_54", bizLicenceRespVO.getIdentificationResult());
        map.put("licence_number", bizLicenceRespVO.getNumber());

        if (bizLicenceRespVO.getPersonList() != null && !bizLicenceRespVO.getPersonList().isEmpty()) {
            List<String> personNames = bizLicenceRespVO.getPersonList().stream().map(BizLicencePersonDO::getWorkerName).collect(Collectors.toList());
            String persons = String.join(",", personNames);
            map.put("persons", persons);
        }

        List<BizLicenceSafeMeasuresDO> measuresDOList = bizLicenceRespVO.getSafeMeasuresList();
        if (measuresDOList != null && !measuresDOList.isEmpty()) {
            for (int i = 1; i <= measuresDOList.size(); i++) {
                map.put("mearsureContent" + i, measuresDOList.get(i - 1).getContent());
                map.put("applicable" + i, measuresDOList.get(i - 1).getApplicable() ? "是" : "否");
                map.put("qualified" + i, measuresDOList.get(i - 1).getQualified() ? "是" : "否");
            }
        }
        return map;
    }

//    public Map<String,Object>


    public void manipulatePdf(PdfReader reader, String imageUrl, String text, PdfStamper ps, int pageNum, BaseFont bf) throws IOException, DocumentException {
        // 新增空白页
        ps.insertPage(pageNum, reader.getPageSizeWithRotation(1));
//        // 水印
//        ImageRemarkUtil.markImageByText("20202020202", imageUrl, targetImageUrl);
        PdfContentByte over = ps.getOverContent(pageNum);

        // 添加描述
        over.setTextMatrix(100, 720);
        over.setFontAndSize(bf, 20);
        over.showText(text);

        Image image = Image.getInstance(imageUrl);
        PdfImage stream = new PdfImage(image, "", null);
        PdfIndirectObject ref = ps.getWriter().addToBody(stream);
        image.setDirectReference(ref.getIndirectReference());
        // 图片位置
        image.setAbsolutePosition(100, 300);
        // 图片大小
        image.scaleToFit(400, 400);
        over.addImage(image);

    }

    public void manipulatePersonPdf(int pageNum, String imageUrl, PdfStamper ps, int i, BaseFont bf) throws IOException, DocumentException {

//        // 水印
//        ImageRemarkUtil.markImageByText("20202020202", imageUrl, targetImageUrl);
        PdfContentByte over = ps.getOverContent(pageNum);

        // 添加描述
        over.setTextMatrix(100, 720);
        over.setFontAndSize(bf, 20);
        over.showText("作业人员签名");

        Image image = Image.getInstance(imageUrl);
        PdfImage stream = new PdfImage(image, "", null);
        PdfIndirectObject ref = ps.getWriter().addToBody(stream);
        image.setDirectReference(ref.getIndirectReference());
        // 图片位置
        image.setAbsolutePosition(250, 700 - (i + 1) * 70);
        // 图片大小
        image.scaleToFit(60, 60);
        over.addImage(image);

    }


    // 签章图片
    private static void addImageToPdf(AcroFields form, PdfStamper stamper, String filePath, String column) throws DocumentException, IOException {

        // 通过域名获取所在页和坐标，左下角为起点
        int pageNo = form.getFieldPositions(column).get(0).page;
        Rectangle signRect = form.getFieldPositions(column).get(0).position;
        float x = signRect.getLeft() + (signRect.getRight() - signRect.getLeft()) / 2;
        float y = signRect.getTop();

        // 获取操作的页面
        PdfContentByte under = stamper.getOverContent(pageNo);
        // 读图片
        Image image = Image.getInstance(filePath);
        PdfImage stream = new PdfImage(image, "", null);
        PdfIndirectObject ref = stamper.getWriter().addToBody(stream);
        image.setDirectReference(ref.getIndirectReference());
        // 根据域的大小缩放图片
        image.scaleToFit(signRect.getBottom() - signRect.getTop(), signRect.getBottom() - signRect.getTop());
        // 添加图片并设置位置（个人通过此设置使得图片垂直水平居中，可参考，具体情况已实际为准）
        image.setAbsolutePosition(x, y);

        under.addImage(image);
    }

}
